<%--
  Created by IntelliJ IDEA.
  User: ykm
  Date: 2018/8/6
  Time: 16:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Bootstrap 实例 - 模态框（Modal）插件</title>

</head>

<body>
<div class="modal-header" style="border-bottom: none;">
    <button type="button" class="btn btn-default pull-right">
        <i class="fa fa-check"></i>
        保存
    </button>
    <h4 class="modal-title" id="myModalLabel">
        新增角色
    </h4>
    <hr class="boder-t-a"/>
</div>
<div class="modal-body" style="padding-top: 0px;">
    <form id="xsjh" action="/role_add" method="post">
        <div class="mybody">
            <div class="text-center-b">
                <span style="background-color: white; padding: 2px 10px;">给用户分配角色</span>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group overflow">
                        <label class="control-label col-md-4">角色列表：</label>
                        <div class="col-md-8">
                            <select name="roleIds" class="selectpicker" data-live-search="true" multiple
                                    data-live-search="true" title="可多选" id="roles">
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div style="height: 50px; "></div>
        </div>
    </form>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-primary" data-dismiss="modal">关闭</button>
    <button class="btn btn-default" type="button" id="mysubmit"><i class="fa fa-check"></i>
        保存
    </button>
</div>


<script>
    $(function () {
        $("#user_grant_role").on('hidden.bs.modal', function () {
            open_modal = null;
            $(this).removeData('bs.modal');
        });
        $(".selectpicker").selectpicker({
            noneSelectedText: '未选'
        });

        $('.selectpicker').selectpicker('refresh');
        //下拉数据加载
        $.ajax({
            type: 'get',
            url: "/get_role_nodes?userId=" + open_modal,
            async: false,
            dataType: 'json',
            success: function (datas) {//返回list数据并循环获取
                var select = $("#roles");
                for (var i = 0; i < datas.list.length; i++) {
                    if (datas.list[i].selected.toString().toLowerCase() === "true") {
                        select.append("<option value='" + datas.list[i].roleId + "' selected>"
                            + datas.list[i].roleName + "</option>");
                    } else {
                        select.append("<option value='" + datas.list[i].roleId + "'>"
                            + datas.list[i].roleName + "</option>");
                    }
                }
                // $('.selectpicker').selectpicker('val', '');
                $('.selectpicker').selectpicker('refresh');
            }
        });

        $("#xsjh").bootstrapValidator({});

        $("#mysubmit").on("click", function () {
            //获取表单对象
            var bootstrapValidator = $("#xsjh").data('bootstrapValidator');
            //手动触发验证
            bootstrapValidator.validate();
            if (bootstrapValidator.isValid()) {
                // alert("表单序列化结果：" + $("#xsjh").serialize());
                var a = JSON.stringify($("#xsjh").serialize());
                // alert(a);
                var b = new Array();
                b = a.split('&');
                var ids = new Array();
                for (var i = 0; i < b.length; i++) {
                    ids.push(b[i].replace(/[^0-9]/ig, ""));
                }
                // alert(ids);
                // alert(typeof ids);

                $.ajax({
                    url: '/grant_role_to_user',
                    type: "POST",
                    async: false,
                    dataType: 'json',
                    contentType: 'application/x-www-form-urlencoded',
                    data: {'userId': open_modal, 'ids': JSON.stringify(ids)},
                    success: function (result) {
                        if (result.code == 200) {
                            swal("成功", result.msg, "success");
                            $('#user_grant_role').modal('hide');
                            //表单重置
                            $("#xsjh")[0].reset();
                            $("#table111").bootstrapTable('refresh');
                        }
                    },
                    error: function (data) {
                        swal("连接服务器错误", "", "error");
                    }
                });
            }
        });

        $("[data-toggle='tooltip' ] ").tooltip();

    });

    function checkSelected() {
        var select = document.getElementById("roles");
        var ids = [];
        for (var i = 0; i < select.length; i++) {
            alert("开始遍历" + i);
            if (select.options[i].selected) {
                var a = select.options[i].value();
                alert(a);
                ids.push(a);
            }
        }
        alert(ids);
    }

    //查看对象的所有属性和方法
    function displayProp(obj) {
        var names = "";
        for (var name in obj) {
            names += name + ": " + obj[name] + ", ";
        }
        alert(names);
    }

    //表单初始化
    // function setForm() {
    //     if (open_modal != null) {
    //         ajax("/role_load?roleId=" + open_modal, function (data) {
    //             // alert(data.oppTheme)
    //             // alert(JSON.stringify(data))
    //             $('#xsjh').append("<input class='hidden' name='roleId' value='" + data.roleId + "'>")
    //             $('input[name="roleName"]').val(data.roleName)
    //         }, function () {
    //             swal("加载失败", result.msg, "error");
    //             $('#add_role').modal('hide')
    //         }, "get", {})
    //     }
    // }
    //
    // function ajax(url, success, error, type, data) {
    //     $.ajax({
    //         url: url,
    //         timeout: 3000,
    //         type: type,
    //         data: data,
    //         dataType: 'json',
    //         contentType: 'application/x-www-form-urlencoded',
    //         success: function (result) {
    //             if (result.code != 200) {
    //                 swal(result.msg, "", "error");
    //                 error()
    //             }
    //             else {
    //                 success(result.data);
    //             }
    //         },
    //         complete: function (XMLHttpRequest, status) {
    //             if (status != "success") {
    //                 swal("连接服务器错误", "", "error");
    //                 error()
    //             }
    //         }
    //     })
    // }
</script>

</body>

</html>